package com.sch.wanandroid.ui.my.collect.addCollect

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sch.wanandroid.network.NetWorkManager
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * Created by Sch.
 * Date: 2020/12/23
 * description:
 */
class AddCollectViewModel : ViewModel() {
    val titleString = MutableLiveData<String>()
    val authorString = MutableLiveData<String>()
    val linkString = MutableLiveData<String>()

    private val _addSuccess = MutableLiveData<Boolean>()
    val addSuccess: LiveData<Boolean> = _addSuccess
    private val _errorMsg = MutableLiveData<String?>()
    val errorMsg: LiveData<String?> = _errorMsg

    init {
        linkString.value = "https://"
    }

    fun addCollect() {
        viewModelScope.launch {
            try {
                val result =
                    NetWorkManager.apiService.addCollect(
                        titleString.value!!,
                        authorString.value!!,
                        linkString.value!!
                    )
                if (result.errorCode != 0) {
                    _errorMsg.value = result.errorMsg
                } else {
                    _addSuccess.value = true
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }
}